package com.weasel.weixin.mp.servlet;

import com.weasel.helper.ClassPathFileReader;
import com.weasel.weixin.commons.accounts.QRCoceResponse;
import com.weasel.weixin.commons.accounts.QRCodeRequest;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * Created by Dylan on 2015/9/28.
 */
public class QRCodeServlet extends WeixinBaseServlet {



    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");

        QRCodeRequest qrCodeRequest = new QRCodeRequest(config);
        try {
            QRCoceResponse qrCoceResponse = qrCodeRequest.getTemporaryQRCode(1);
            String temporaryQRCodeUrl = qrCodeRequest.getQRCodeImageURL(qrCoceResponse.getTicket());

            qrCoceResponse = qrCodeRequest.getForeverQRCode("jd");
            String foreverQRCodeUrl = qrCodeRequest.getQRCodeImageURL(qrCoceResponse.getTicket());

            File qrCodeImage = qrCodeRequest.getQRCode(qrCoceResponse.getTicket(), new File(ClassPathFileReader.getClassPath()));

            response.getWriter().println("<h1>临时二维码:</h1><img src='"+temporaryQRCodeUrl+"' width='100' height='100'></img><br>");
            response.getWriter().println("<h1>永久二维码:</h1><img src='"+foreverQRCodeUrl+"' width='100' height='100'></img><br>");
            response.getWriter().println("<h1>已将永久二维码图片保存到以下位置:"+qrCodeImage.getAbsolutePath()+"</h1><br>");
            response.getWriter().flush();
            response.getWriter().close();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
